import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:stacked/stacked.dart';
import 'package:stacked_services/stacked_services.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/features/home/viewmodels/home_viewmodel.dart';
import 'package:vista/shared/models/moment_shot.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/daily_inspiration_service.dart';
import 'package:vista/shared/services/post_studio.dart';
import 'package:vista/app/router/app_router.dart';
import 'package:vista/shared/utils/flash_notifier.dart';
import 'package:vista/shared/utils/widget_extension.dart';
import 'package:vista/shared/widgets/auth_gate_modal.dart';
import 'package:vista/shared/widgets/complain_bottom_sheet.dart';

/// 首页
class HomeView extends StatelessWidget {
  const HomeView({super.key});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<HomeViewModel>.reactive(
      viewModelBuilder:
          () => HomeViewModel(
            getIt.get<AuthFocus>(),
            getIt.get<DailyInspirationService>(),
            getIt.get<PostStudio>(),
          )..initialize(),
      builder:
          (context, model, child) => Scaffold(
            body: Container(
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/my-background.png'),
                  fit: BoxFit.cover,
                ),
              ),
              child: SafeArea(
                child: [
                  // 固定标题栏
                  _buildHeader(context),
                  // 可滚动内容
                  Expanded(
                    child:
                        model.isBusy
                            ? const Center(child: CircularProgressIndicator())
                            : SingleChildScrollView(
                              child: [
                                    // 每日灵感
                                    _buildDailyInspirationSection(
                                      context,
                                      model,
                                    ),
                                    SizedBox(height: 20.h),
                                    // 两个图片按钮
                                    _buildActionButtonsSection(context),
                                    SizedBox(height: 20.h),
                                    // 摄影动态列表
                                    _buildPhotographyPostsSection(
                                      context,
                                      model,
                                    ),
                                    SizedBox(height: 100.h), // 底部留白
                                  ]
                                  .verticalShot(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.stretch,
                                  )
                                  .frameHorizontal(14.w),
                            ),
                  ),
                ].verticalShot().frameAll(0),
              ),
            ),
          ),
    );
  }

  /// 构建标题栏
  Widget _buildHeader(BuildContext context) {
    return Stack(
      children: [
        // 装饰图片（在文字下方z轴）
        Positioned(
          right: 120.w,
          top: -36.h,
          child: Image.asset(
            'assets/images/home-decoration.png',
            width: 94.w,
            height: 140.h,
            fit: BoxFit.contain,
          ),
        ),
        // 标题栏内容
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 16.h),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 左边文字（三排）
              Expanded(
                child: Container(
                  constraints: BoxConstraints(maxWidth: 260.w),
                  child: [
                    // 第一排
                    Text(
                      'Welcome! Connect you and me with',
                      style: TextStyle(
                        fontSize: 17.sp,
                        height: 1.29,
                        letterSpacing: -0.41,
                        fontWeight: FontWeight.w700,
                        fontFamily:
                            GoogleFonts.oleoScriptSwashCaps(
                              fontWeight: FontWeight.w700,
                            ).fontFamily,
                        color: Colors.white,
                        shadows: [
                          // 黑色边框效果 - 使用多个阴影
                          Shadow(
                            offset: Offset(-1, -1),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(1, -1),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(-1, 1),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(1, 1),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(0, -1),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(0, 1),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(-1, 0),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(1, 0),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                        ],
                      ),
                    ),
                    // 第二排
                    Text(
                      'photos, record and share every',
                      style: TextStyle(
                        fontSize: 17.sp,
                        height: 1.29,
                        letterSpacing: -0.41,
                        fontWeight: FontWeight.w700,
                        fontFamily:
                            GoogleFonts.oleoScriptSwashCaps(
                              fontWeight: FontWeight.w700,
                            ).fontFamily,
                        color: Color(0xFFFFFBDE),
                        shadows: [
                          // 黑色边框效果 - 使用多个阴影
                          Shadow(
                            offset: Offset(-1, -1),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(1, -1),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(-1, 1),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(1, 1),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(0, -1),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(0, 1),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(-1, 0),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(1, 0),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                        ],
                      ),
                    ),
                    // 第三排
                    Text(
                      'moment\'s beauty.',
                      style: TextStyle(
                        fontSize: 17.sp,
                        height: 1.29,
                        letterSpacing: -0.41,
                        fontWeight: FontWeight.w700,
                        fontFamily:
                            GoogleFonts.oleoScriptSwashCaps(
                              fontWeight: FontWeight.w700,
                            ).fontFamily,
                        color: Color(0xFFFFEF73),
                        shadows: [
                          // 黑色边框效果 - 使用多个阴影
                          Shadow(
                            offset: Offset(-1, -1),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(1, -1),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(-1, 1),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(1, 1),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(0, -1),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(0, 1),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(-1, 0),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                          Shadow(
                            offset: Offset(1, 0),
                            blurRadius: 0,
                            color: Colors.black,
                          ),
                        ],
                      ),
                    ),
                  ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
                ),
              ),
              SizedBox(width: 2.w),
              // 右边设置按钮
              GestureDetector(
                onTap: () async {
                  // 检查用户是否登录
                  final currentUser = await getIt<AuthFocus>().getCurrentUser();
                  if (currentUser == null) {
                    // 未登录，显示登录弹窗
                    final result = await showDialog<bool>(
                      context: context,
                      builder: (context) => const AuthGateModal(),
                    );
                    if (result == true && context.mounted) {
                      // 用户点击登录，跳转到登录页面
                      await Navigator.of(context).pushNamed(Routes.login);
                    }
                  } else {
                    // 已登录，直接跳转到设置页面
                    if (context.mounted) {
                      Navigator.of(context).pushNamed(Routes.settings);
                    }
                  }
                },
                child: Image.asset(
                  'assets/images/setup.png',
                  width: 28.w,
                  height: 28.h,
                  fit: BoxFit.contain,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建每日灵感区域
  Widget _buildDailyInspirationSection(
    BuildContext context,
    HomeViewModel model,
  ) {
    if (model.dailyInspirations.isEmpty) {
      return const SizedBox.shrink();
    }

    return Stack(
      clipBehavior: Clip.none,
      children: [
        // 每日灵感容器（宽高比347/210）
        AspectRatio(
          aspectRatio: 347 / 210,
          child: Container(
            decoration: BoxDecoration(
              image: const DecorationImage(
                image: AssetImage('assets/images/daily-box.png'),
                fit: BoxFit.fill,
              ),
            ),
            child: Stack(
              clipBehavior: Clip.none,
              children: [
                // 底层装饰图片
                Positioned(
                  right: 20.w,
                  top: -0.h,
                  child: Image.asset(
                    'assets/images/box-decoration.png',
                    width: 92.w,
                    height: 92.h,
                    fit: BoxFit.contain,
                  ),
                ),
                // 内层容器（宽高比311/174）
                Positioned(
                  left: 8.w,
                  right: 12.w,
                  top: 28.h,
                  bottom: 8.h,
                  child: AspectRatio(
                    aspectRatio: 311 / 174,
                    child: Container(
                      decoration: BoxDecoration(
                        image: const DecorationImage(
                          image: AssetImage('assets/images/dianyin.png'),
                          fit: BoxFit.fill,
                        ),
                      ),
                      child: Row(
                        children:
                            model.dailyInspirations
                                .map(
                                  (inspiration) => Expanded(
                                    child: _buildInspirationItem(
                                      context,
                                      inspiration,
                                      model,
                                    ),
                                  ),
                                )
                                .toList(),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建单个灵感项
  Widget _buildInspirationItem(
    BuildContext context,
    inspiration,
    HomeViewModel model,
  ) {
    final user = model.getUserById(inspiration.authorId);
    return GestureDetector(
      onTap: () {
        getIt.get<NavigationService>().navigateTo(
          Routes.inspirationDetail,
          arguments: {'inspirationId': inspiration.id},
        );
      },
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 2.w),
        child: AspectRatio(
          aspectRatio: 105 / 140,
          child: Hero(
            tag: 'inspiration_${inspiration.id}',
            child: Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(inspiration.image),
                  fit: BoxFit.cover,
                ),
              ),
              child: Stack(
                children: [
                  // 底部蒙层
                  Positioned(
                    left: 0,
                    right: 0,
                    bottom: 0,
                    child: Container(
                      padding: EdgeInsets.all(4.w),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                          colors: [
                            Colors.transparent,
                            Colors.black.withOpacity(0.7),
                          ],
                        ),
                      ),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          // 用户头像（正方形）
                          GestureDetector(
                            onTap: () async {
                              if (user == null) return;
                              // 检查是否是当前用户
                              final currentUser =
                                  await getIt<AuthFocus>().getCurrentUser();
                              if (currentUser != null &&
                                  currentUser.id == user.id) {
                                return; // 是自己的头像，不跳转
                              }
                              // 跳转到他人主页
                              if (context.mounted) {
                                await Navigator.of(context).pushNamed(
                                  Routes.otherProfile,
                                  arguments: {'userId': user.id},
                                );
                              }
                            },
                            child: Container(
                              width: 26.w,
                              height: 26.w,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(2.r),
                                color: Colors.white,
                                image:
                                    user?.avatar != null
                                        ? DecorationImage(
                                          image: AssetImage(user!.avatar!),
                                          fit: BoxFit.cover,
                                        )
                                        : null,
                                boxShadow: [
                                  // 右下角阴影效果
                                  BoxShadow(
                                    offset: Offset(2, 2),
                                    blurRadius: 4,
                                    color: Colors.black.withOpacity(0.3),
                                  ),
                                ],
                              ),
                              child:
                                  user?.avatar == null
                                      ? Center(
                                        child: Icon(
                                          Icons.person,
                                          size: 16.w,
                                          color: Colors.grey,
                                        ),
                                      )
                                      : null,
                            ),
                          ),
                          SizedBox(width: 6.w),
                          // 用户名和签名 Column
                          Expanded(
                            child: [
                              // 第一排：用户名
                              Text(
                                user?.username ?? 'Unknown',
                                style: TextStyle(
                                  fontSize: 12.sp,
                                  color: Colors.white,
                                  fontFamily:
                                      GoogleFonts.alegreyaSans(
                                        fontWeight: FontWeight.w500,
                                      ).fontFamily,
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                              // 第二排：用户签名
                              if (user?.username != null)
                                Text(
                                  '@ ${user?.username}',
                                  style: TextStyle(
                                    fontSize: 12.sp,
                                    color: Colors.white.withOpacity(0.9),
                                    fontFamily:
                                        GoogleFonts.alegreyaSans(
                                          fontWeight: FontWeight.w400,
                                        ).fontFamily,
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                            ].verticalShot(
                              crossAxisAlignment: CrossAxisAlignment.start,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建操作按钮区域
  Widget _buildActionButtonsSection(BuildContext context) {
    return [
      Expanded(
        child: AspectRatio(
          aspectRatio: 168 / 216,
          child: GestureDetector(
            onTap: () {
              getIt.get<NavigationService>().navigateTo(Routes.skillsClass);
            },
            child: Image.asset(
              'assets/images/skills-class.png',
              fit: BoxFit.fill,
            ),
          ),
        ),
      ),
      SizedBox(width: 12.w),
      Expanded(
        child: AspectRatio(
          aspectRatio: 168 / 216,
          child: GestureDetector(
            onTap: () {
              getIt.get<NavigationService>().navigateTo(
                Routes.themeChallengeList,
              );
            },
            child: Image.asset(
              'assets/images/theme-challenge.png',
              fit: BoxFit.fill,
            ),
          ),
        ),
      ),
    ].horizontalGallery();
  }

  /// 构建摄影动态列表
  Widget _buildPhotographyPostsSection(
    BuildContext context,
    HomeViewModel model,
  ) {
    if (model.photographyPosts.isEmpty) {
      return const SizedBox.shrink();
    }

    final postWidgets = <Widget>[
      // 标题
      Text(
        'Captured Moments',
        style: TextStyle(
          fontSize: 16.sp,
          fontFamily:
              GoogleFonts.alegreyaSans(fontWeight: FontWeight.w800).fontFamily,
          color: Colors.black87,
        ),
      ),
      SizedBox(height: 14.h),
    ];

    // 添加动态列表
    for (int i = 0; i < model.photographyPosts.length; i++) {
      postWidgets.add(
        _buildPostItem(context, model.photographyPosts[i], model),
      );
      if (i < model.photographyPosts.length - 1) {
        postWidgets.add(SizedBox(height: 14.h));
      }
    }

    return postWidgets.verticalShot(
      crossAxisAlignment: CrossAxisAlignment.start,
    );
  }

  /// 构建单个动态项
  Widget _buildPostItem(
    BuildContext context,
    MomentShot post,
    HomeViewModel model,
  ) {
    final user = model.getUserById(post.authorId);
    // 确保至少有三张图片，不足则用第一张填充
    final displayImages = <String>[];
    if (post.images.isNotEmpty) {
      displayImages.addAll(post.images.take(3));
      // 如果不足3张，用第一张填充
      while (displayImages.length < 3) {
        displayImages.add(post.images.first);
      }
    }

    return GestureDetector(
      onTap: () async {
        await getIt.get<NavigationService>().navigateTo(
          Routes.photographyDetail,
          arguments: {'postId': post.id},
        );
        // 返回后刷新列表
        await model.refresh();
      },
      child: AspectRatio(
        aspectRatio: 347 / 242,
        child: Stack(
          children: [
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(6.r),
                boxShadow: [
                  BoxShadow(
                    color: Color(0xFF000000),
                    blurRadius: 0,
                    offset: Offset(4, 4),
                    spreadRadius: 0,
                  ),
                ],
              ),
              child: Row(
                children:
                    displayImages.asMap().entries.map((entry) {
                      final index = entry.key;
                      final image = entry.value;
                      final isFirst = index == 0;

                      return Expanded(
                        child: Stack(
                          children: [
                            // 图片
                            ClipRRect(
                              borderRadius: BorderRadius.only(
                                topLeft:
                                    index == 0
                                        ? Radius.circular(6.r)
                                        : Radius.zero,
                                bottomLeft:
                                    index == 0
                                        ? Radius.circular(6.r)
                                        : Radius.zero,
                                topRight:
                                    index == 2
                                        ? Radius.circular(6.r)
                                        : Radius.zero,
                                bottomRight:
                                    index == 2
                                        ? Radius.circular(6.r)
                                        : Radius.zero,
                              ),
                              child: Image.asset(
                                image,
                                width: double.infinity,
                                height: double.infinity,
                                fit: BoxFit.cover,
                              ),
                            ),
                            // 第一张图片左上角显示发布者头像
                            if (isFirst && user != null)
                              Positioned(
                                left: 6.w,
                                top: 0.h,
                                child: ClipRRect(
                                  borderRadius: BorderRadius.only(
                                    bottomLeft: Radius.circular(50.r),
                                    bottomRight: Radius.circular(50.r),
                                  ),
                                  child: BackdropFilter(
                                    filter: ImageFilter.blur(
                                      sigmaX: 10,
                                      sigmaY: 10,
                                    ),
                                    child: Container(
                                      decoration: BoxDecoration(
                                        color: Colors.white.withValues(
                                          alpha: 0.60,
                                        ),
                                        borderRadius: BorderRadius.only(
                                          bottomLeft: Radius.circular(50.r),
                                          bottomRight: Radius.circular(50.r),
                                        ),
                                        boxShadow: [
                                          BoxShadow(
                                            color: Colors.black.withValues(
                                              alpha: 0.40,
                                            ),
                                            blurRadius: 4,
                                          ),
                                        ],
                                      ),
                                      padding: EdgeInsets.only(
                                        left: 2.w,
                                        right: 2.w,
                                        bottom: 3.w,
                                        top: 16.w,
                                      ),
                                      child: Container(
                                        width: 40.w,
                                        height: 40.w,
                                        decoration: BoxDecoration(
                                          shape: BoxShape.circle,
                                          color: Colors.white,
                                          border: Border.all(
                                            color: Colors.white,
                                            width: 2,
                                          ),
                                        ),
                                        child: ClipOval(
                                          child:
                                              user.avatar != null
                                                  ? Image.asset(
                                                    user.avatar!,
                                                    width: 40.w,
                                                    height: 40.w,
                                                    fit: BoxFit.cover,
                                                  )
                                                  : Icon(
                                                    Icons.person,
                                                    size: 24.w,
                                                    color: Colors.grey,
                                                  ),
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                          ],
                        ),
                      );
                    }).toList(),
              ),
            ),
            // 右上角举报icon（带蒙层）
            Positioned(
              right: 8.w,
              top: 8.h,
              child: GestureDetector(
                onTap: () async {
                  // 显示举报弹窗
                  await ComplainHelper.unveil(
                    context,
                    onComplain: (reason) async {
                      // 举报成功，显示提示并删除动态
                      FlashNotifier.flashSuccess(
                        'Report submitted successfully',
                      );
                      await model.deletePost(post.id);
                    },
                  );
                },
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(4.r),
                  child: BackdropFilter(
                    filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                    child: Container(
                      padding: EdgeInsets.all(4.w),
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: Colors.black.withOpacity(0.2),
                      ),
                      child: Icon(
                        Icons.more_horiz,
                        size: 20.w,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ),
            ),
            // 右下角访问次数（带蒙层）
            Positioned(
              right: 8.w,
              bottom: 8.h,
              child: ClipRRect(
                borderRadius: BorderRadius.circular(4.r),
                child: BackdropFilter(
                  filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                  child: Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 10.w,
                      vertical: 6.h,
                    ),
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(4.r),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Image.asset(
                          'assets/images/eye.png',
                          width: 16.w,
                          height: 16.h,
                          fit: BoxFit.contain,
                          color: Colors.white,
                        ),
                        SizedBox(width: 4.w),
                        Text(
                          '${post.viewCount}',
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: Colors.white,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
